package cn.peng.stu4teach.util.update;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

/**
 * 功用：Apk 下载的广播接收器
 */
public class ApkDownloadReceiver extends BroadcastReceiver {
    private final String TAG = getClass().getSimpleName();

    @Override
    public void onReceive (Context context, Intent intent) {
        ToastUtils.showShort("下载完成了");
        String action = intent.getAction();
        if (TextUtils.isEmpty(action)) {
            LogUtils.d(TAG, "action is empty");
            return;
        }
        switch (action) {
            case DownloadManager.ACTION_DOWNLOAD_COMPLETE:
                //获取下载ID
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                checkDownloadStatus(context, downloadManager, downloadId);
                break;
            case DownloadManager.ACTION_NOTIFICATION_CLICKED:
                //如果还未完成下载，跳转到下载中心
                Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                viewDownloadIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(viewDownloadIntent);
                break;
            default:
                break;
        }
    }

    /**
     * 检查下载状态并安装
     * 也可以使用如下方式获取 URI
     * String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
     * Uri uri = Uri.parse(uriString);
     * <p></>
     * 也可以使用FileProvider转换Uri：
     */
    private void checkDownloadStatus (Context context, DownloadManager downloadManager, long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
            if (columnIndex < 0) {
                return;
            }

            switch (cursor.getInt(columnIndex)) {
                case DownloadManager.STATUS_SUCCESSFUL:
                    // 下载成功，安装APK
                    Uri uri = downloadManager.getUriForDownloadedFile(downloadId);
                    // 使用FileProvider转换Uri
                    installApk(context, uri);
                    break;
                case DownloadManager.STATUS_FAILED:
                    // 下载失败，可以提供重试机制
                    Toast.makeText(context, "下载失败，请重试", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
        cursor.close();
    }

    /**
     * 安装apk
     */
    private void installApk (@NonNull Context pAppCtx, Uri uri) {
        if (null == uri) {
            Toast.makeText(pAppCtx, "下载失败，请重试", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 给即将启动的Activity授予临时的读取权限，针对传递的URI所指向的文件或资源。
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        pAppCtx.startActivity(intent);
    }
}
